<?php
/*
Array $data: Data Array
String $tagname: Root Element Name
String $tagid: Unique Column Name
*/
function save_data($data, $tagname, $tagid = "") {
	$doc = new DOMDocument();
	$datafile = 'data/'.$tagname.".xml";
				
  	if(file_exists($datafile)) {
  		$doc->load($datafile); 
		$r = $doc->getElementsByTagName($tagname)->item(0);
  	} else {
		$r = $doc->createElement($tagname);
  		$doc->appendChild( $r );
	}
	
	$xpath = new DOMXPath( $doc );			

   if(count($data) > 0) {

	   $columns = array_keys(current($data));   
   
  		foreach( $data as $row ) {
			$rowName = (string) substr($tagname, 0, (strlen($tagname)-1));
	  		$b = $doc->createElement($rowName);
	  		
	  		foreach( $columns as $column ) {
	  			$name = $doc->createElement($column);
	  			$name->appendChild($doc->createTextNode($row[$column]));
	  			$b->appendChild($name);
			}
			
			$expression = '//'.$rowName.'[@'.$tagid.'="'.$row[$tagid].'"]';
			
			$elements = $xpath->query($expression);
						
			if(empty($elements->length)) {
	  			$newRecord = $r->appendChild($b);
			
				if(!empty($tagid))  		
	  				$newRecord->setAttribute($tagid, $row[$tagid]);
	  		}
  		}
  }
  
  $doc->saveXML();
  $doc->formatOutput = true;  
  $doc->save($datafile);
}

function read_data($filename, $tagname="") {
	$doc = new DOMDocument();

	if(!empty($tagname)) {
		$rowName = (string) substr($tagname, 0, (strlen($tagname)-1));
	} else {
		$tagname = $filename;
		$rowName = (string) substr($tagname, 0, (strlen($tagname)-1));
	}
	
	$datafile = 'data/'.$tagname.".xml";
				
  	if(file_exists($datafile)) {
  		$doc->load($datafile); 
		$r = $doc->getElementsByTagName($tagname)->item(0);
		$xpath = new DOMXPath( $doc );
		$expression = '//'.$rowName;
		$elements = $xpath->query($expression);
		$data = array();
		if(!empty($elements->length)) {
			foreach($elements as $key => $element) {
				$row = array();
				$columns = $element->childNodes; 
				foreach($columns as $key1 => $element1) {
					if(!empty($element1->tagName))
						$row[$element1->tagName] = $element1->nodeValue;
				}
				
				if(count($row) > 0)
					$data[] = $row;
			}				
		}
		
		return $data;
  	}
}

function makeNumber($value) {
		$value = preg_replace('/[^0-9\.]/', '', $value);
		return $value;
}

function makeName($value) {
		$value = preg_replace('/[^A-Za-z0-9_\-]/', '', $value);
		$value = strtolower($value);
		return $value;
}

function filterOutput($value) {
		$value = strip_tags($value);
		$value = preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $value);
		$value = trim($value);
		return $value;
}

function display_array($key, $array, &$depth = 0) {
	
	foreach($array as $name => $value) {

		if(is_array($value)) {
			$depth += 1;
			display_array($name, $value, $depth);
		} else {
			$value = stripslashes($value);
			echo '<input onfocus="this.select();" type="text" name="'.$key.'['.$name.']" value="'.$value.'"  size="55" />';
			echo $key.'['.$name."] <br />\n";		
		}
	}
}

if(!empty($_POST['debug'])) {
	$debug_form = 1;
} else {
	$debug_form = 0;
}

if(!empty($_POST['process_text'])) {
	$process_text = 1;
} else {
	$process_text = 0;
}

$display_form = 0;
$information = array();

if(!empty($_POST['process'])) {	
	
	$contents = stripslashes($_POST['contents']);

	$actions = array('get_links', 'save_links');
	$action = $_POST['action'];
	$url = $_POST['url'];

	$oldSetting = libxml_use_internal_errors( true );
	libxml_clear_errors();
	$html = new DOMDocument();

	if($process_text) {
		$html->loadHtml( $contents );
	} else {
		$html->loadHtmlFile( $contents );
	}

	$xpath = new DOMXPath( $html );
	
	foreach($actions as $action) {
		switch($action) {
			case 'get_links':
				
				$elements = $xpath->query( '//li[@class="site-listing"]' );		
				
				foreach($elements as $key => $element) {					
					$rank = filterOutput($xpath->query('div[@class="count"]', $element)->item(0)->nodeValue);
					$link = "http://www.".filterOutput($xpath->query('div[@class="desc-container"]/span', $element)->item(0)->nodeValue);
					$heading = filterOutput($xpath->query('div[@class="desc-container"]/h2/a', $element)->item(0)->nodeValue);
					$rating = filterOutput($xpath->query('ul[@class="mini-nav"]/li/div', $element)->item(0)->getAttribute('title'));					
					$information[$action][] = array(
						'rank' => $rank,
						'link' => $link,
						'heading' => $heading,
						'rating' => $rating,
					);
				}
				
			break;
			case 'save_links':
				save_data($information['get_links'], 'links', 'link');		
			break;
			default:
				die('No Action Specified');
			break;
		}
	}	
	
	if($debug_form) {
		echo "<pre>";
		print_r($information);
		echo "</pre>";
//		exit;
	}
	
	libxml_clear_errors();
	libxml_use_internal_errors( $oldSetting );


//	print_r($information);
//	die;	
}

//$all_links =  read_data('links');
//save_data($all_links, 'records', 'link');
//print_r($all_links);
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252" />
<title>Extract</title>
</head>
<body>
<?php if(0) { ?>

<?php } else { ?>
<form id="form1" name="form1" method="post" action="#">
  Debug:
  <input type="checkbox" value="1" name="debug"  <?=($debug_form) ? 'checked' : ''?> />
  Process Text :
  <input type="checkbox" value="1" name="process_text" <?=($process_text) ? 'checked' : ''?> />
  <input name="process" type="submit" id="process" value="Process" />
  <br />
  <textarea name="contents" cols="50" rows="10" id="contents"><?=$contents?></textarea>
  <br />
</form>
<?php } ?>
</body>
</html>